package com.net.xpay.operator.controller.operator.common;

import com.google.common.base.Strings;
import com.net.common.exception.BusinessException;
import com.net.common.util.SerializationUtil;
import com.net.xpay.common.helper.RedisHelper;
import com.net.xpay.common.service.OperatorUserService;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.xpay.core.constant.RedisKey;
import com.net.xpay.core.helper.ImageCodeHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
@RestController
@RequestMapping("/common/image-code")
@Api(tags = "公共/图形验证", description = "公共 图形验证 net")
public class ImageCodeController {

    @Autowired
    private OperatorUserService operatorUserService;

    @Autowired
    private ImageCodeHelper imageCodeHelper;

    @Autowired
    private RedisHelper redisHelper;


    /**
     * 生成验证码
     *
     * @param request
     * @param response
     * @param codeKey  由前端在请求获取验证码时，传入的随机数
     */
    @ApiOperation("生成图形验证码")
    @GetMapping(value = "/get-code")
    public void getImageCode(HttpServletRequest request, HttpServletResponse response, String codeKey) {

        try {
            // 设置response
            response.setContentType("image/jpeg");
            response.setDateHeader("Expire", 0);
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");

            // 响应验证码
            imageCodeHelper.getImageCode(request, response, codeKey);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 校验验证码
     *
     * @param codeKey 由前端在请求获取验证码时，传入的随机数，该值必须与获取验证码时传递的参数一致
     * @param code    用户输入的验证码
     * @return
     */
    @ApiOperation("验证图形验证码")
    @PostMapping(value = "/check-code")
    public String checkImageCode(@RequestParam String codeKey, @RequestParam String code) {
        try {
            // 在实际开发中，在redis中获取验证码
            String imageCode = null;
            Object statCache = redisHelper.get(RedisKey.IMAGE_CODE + codeKey);
            if (statCache != null) {
                imageCode = SerializationUtil.str2Object(statCache.toString(), String.class);
            }

            // codeKey 作为redis的key
            if (Strings.isNullOrEmpty(imageCode)){
                throw new BusinessException(PoseidonErrorCode.UNKNOWN_ERROR, "系统异常");
            }

            if(!imageCode.equals(code)){
                return "验证失败";
            }

            return "验证成功";
        } catch (Exception e) {
            log.error("验证码校验失败", e);
            return "验证失败";
        }
    }



}
